//
//  GameResult.m
//  MemoPocker
//
//  Created by Jose Luis Ferreyra on 12/07/13.
//  Copyright (c) 2013 Dharma. All rights reserved.
//

#import "GameResult.h"

@interface GameResult()
@property (readwrite, nonatomic) NSDate *start;
@property (readwrite, nonatomic) NSDate *end;
@property (readwrite, nonatomic) NSTimeInterval duration;



@end
@implementation GameResult


-(id) init
{
    self = [super init];
    if (self)
    {
        _start = [NSDate date];
        _end = _start;
    }
    return self;
}

- (NSTimeInterval)duration
{
    return [self.end timeIntervalSinceDate: self.start];
}


- (void) setScore:(int)score
{
    _score = score;
    self.end = [NSDate date];
    [self synchronize];
}

#define ALL_RESULT_KEY @"All_user_games"

-(void) synchronize
{
    NSMutableDictionary *mutableGameResultFromUserDefaults = [[[NSUserDefaults standardUserDefaults] dictionaryForKey:ALL_RESULT_KEY] mutableCopy];
    if (!mutableGameResultFromUserDefaults)
    {
        mutableGameResultFromUserDefaults = [[NSMutableDictionary alloc] init];
    }
    mutableGameResultFromUserDefaults[[self.start description]] = [self asPropertyList];
    [[NSUserDefaults standardUserDefaults] setObject:mutableGameResultFromUserDefaults forKey: ALL_RESULT_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#define START_KEY @"StartDate"
#define END_KEY @"EndDate"
#define SCORE_KEY @"Score"

- (id) asPropertyList
{
    return @{ START_KEY: self.start, END_KEY: self.end, SCORE_KEY: @(self.score)};
}

+ (NSArray *) allGameResults
{
    NSMutableArray *allResults = [[NSMutableArray alloc] init];
    for (id plist in [[[NSUserDefaults standardUserDefaults] dictionaryForKey:ALL_RESULT_KEY] allValues]) {
        GameResult *gameResult = [[GameResult alloc] initFromPropertyList:plist];
        [allResults addObject: gameResult];
    }
    return allResults;
}

//convienient initializer
- (id)initFromPropertyList: (id) pslist
{
    self = [super init];
    if ([pslist isKindOfClass:[NSDictionary class]])
    {
        NSDictionary * result = (NSDictionary *) pslist;
        _start = result[START_KEY];
        _end = result[END_KEY];
        _score = [result[SCORE_KEY] intValue];
        if (!self.start || !self.end) self= Nil;
    }
return self;

}
@end
